#!/usr/bin/env python3
"""
机器学习课程演示脚本
Machine Learning Course Demo Script
"""

import sys
import importlib.util
from pathlib import Path
from typing import List, Dict

def get_available_weeks() -> Dict[str, Path]:
    """获取可用的周次"""
    current_dir = Path.cwd()
    weeks = {}
    
    for week_dir in current_dir.glob("Week*"):
        if week_dir.is_dir():
            week_num = week_dir.name.split('_')[0].replace('Week', '')
            weeks[week_num] = week_dir
    
    return weeks

def list_week_files(week_path: Path) -> List[Path]:
    """列出周次目录下的Python文件"""
    return list(week_path.glob("*.py"))

def run_week_demo(week_num: str):
    """运行指定周次的演示"""
    weeks = get_available_weeks()
    
    if week_num not in weeks:
        print(f"❌ 未找到第{week_num}周的内容")
        print(f"可用的周次: {', '.join(sorted(weeks.keys()))}")
        return
    
    week_path = weeks[week_num]
    python_files = list_week_files(week_path)
    
    if not python_files:
        print(f"❌ 第{week_num}周目录下没有找到Python文件")
        return
    
    print(f"🚀 运行第{week_num}周的演示...")
    print(f"📁 目录: {week_path}")
    
    # 运行主要的Python文件
    main_file = None
    for py_file in python_files:
        if py_file.name != "README.md":
            main_file = py_file
            break
    
    if main_file:
        print(f"📄 执行文件: {main_file.name}")
        
        # 动态导入并执行
        spec = importlib.util.spec_from_file_location("demo_module", main_file)
        if spec and spec.loader:
            module = importlib.util.module_from_spec(spec)
            sys.modules["demo_module"] = module
            spec.loader.exec_module(module)
            
            # 尝试调用主函数
            if hasattr(module, 'main'):
                module.main()
            elif hasattr(module, 'demonstrate_' + week_path.name.lower().replace('week', '').split('_')[1]):
                # 尝试调用演示函数
                demo_func_name = 'demonstrate_' + week_path.name.lower().replace('week', '').split('_')[1]
                if hasattr(module, demo_func_name):
                    getattr(module, demo_func_name)()
        
        print(f"✅ 第{week_num}周演示完成")
    else:
        print(f"❌ 未找到可执行的Python文件")

def show_help():
    """显示帮助信息"""
    print("""
🎓 机器学习课程演示工具

用法:
    ml-demo <week_number>    # 运行指定周次的演示
    ml-demo list            # 列出所有可用的周次
    ml-demo help            # 显示此帮助信息

示例:
    ml-demo 1               # 运行第1周的演示
    ml-demo 15              # 运行第15周的演示
    ml-demo list            # 列出所有周次

📚 课程内容:
    Week 1-4:   基础理论 (导论、可行性、线性模型、梯度下降)
    Week 5-8:   核心理论 (误差噪声、逻辑回归、二阶方法、泛化)
    Week 9-12:  高级理论 (VC维度、方差偏差、过拟合、正则化)
    Week 13-16: 实用方法 (SGD、神经网络、SVM、核方法)
    """)

def list_weeks():
    """列出所有可用的周次"""
    weeks = get_available_weeks()
    
    if not weeks:
        print("❌ 未找到任何课程内容")
        return
    
    print("📚 可用的课程周次:")
    print("=" * 50)
    
    for week_num in sorted(weeks.keys(), key=int):
        week_path = weeks[week_num]
        readme_path = week_path / "README.md"
        
        # 尝试读取README获取标题
        title = "未知主题"
        if readme_path.exists():
            try:
                with open(readme_path, 'r', encoding='utf-8') as f:
                    first_line = f.readline().strip()
                    if first_line.startswith('#'):
                        title = first_line.lstrip('#').strip()
            except:
                pass
        
        python_files = list_week_files(week_path)
        file_count = len(python_files)
        
        print(f"Week {week_num:>2}: {title}")
        print(f"         📁 {week_path.name}")
        print(f"         📄 {file_count} 个Python文件")
        print()

def main():
    """主函数"""
    if len(sys.argv) < 2:
        show_help()
        return
    
    command = sys.argv[1].lower()
    
    if command == "help" or command == "-h" or command == "--help":
        show_help()
    elif command == "list" or command == "ls":
        list_weeks()
    elif command.isdigit():
        week_num = command.zfill(2)  # 补零到两位数
        run_week_demo(week_num)
    else:
        print(f"❌ 未知命令: {command}")
        print("使用 'ml-demo help' 查看帮助信息")

if __name__ == "__main__":
    main()